function [selection,trialtype] = sternberg_files(filenames,n_trials,n_load)
%   [selection,match] = sternberg_files(filenames,ntrials)
%       Picks at random ntrials groups of filenames

% Keep a persistent index of previously used images
persistent already_used;
n=length(filenames);
usable =1:n;
% Exclude images that have been previously used
usable(already_used) = [];
n_usable=length(usable);
% Half of trails are match (vs non match)
trialtype = zeros(1,n_trials);
n_match = ceil(n_trials/2);
n_nomatch = n_trials-n_match;
% Which image is repeated in the matching trials:
trialtype(1:n_match) = mod((1:n_match)-1,n_load)+1;
% Number of unique images needed
n_unique = n_trials*n_load+n_nomatch;
if n_unique > n_usable
    warning('Not enough images!')
    n_missing = n_unique - n_usable;
    trialtype(n_match+[1:n_missing])=1+floor(rand(1,n_missing)*n_load); 
    n_unique = n_usable;
end
% Finally we permute trial order
trialtype = trialtype(randperm(n_trials));
% And make sure we do not have bizarre series:
bad=1;
% while bad
%     bad = any(all([...
%         diff(trialtype(1:end-2));...
%         diff(trialtype(2:end-1));...
%         diff(trialtype(3:end  ))]==0,1));
% end
fprintf('Sternberg Trial types: %s\n',sprintf('%d ', trialtype));

% Now get the images:
sel = randperm(n_usable);
sel = sel(1:n_unique);
selection = reshape(filenames(sel(1:end-n_nomatch)),n_load,n_trials);
selection(n_load+1,trialtype==0) = filenames(sel(end-n_nomatch+1:end));
for i=find(trialtype>0)
    selection(n_load+1,i)=selection(trialtype(i),i);
end
already_used = [already_used sel];
